"use client";

import Link from "next/link";
import { useEffect, useMemo, useState } from "react";
import {
  Bot,
  Braces,
  Briefcase,
  Building2,
  Clapperboard,
  Dna,
  Factory,
  GraduationCap,
  Layers,
  MessagesSquare,
  Music,
  PanelLeftClose,
  PanelLeftOpen,
  Palette,
  PenLine,
  PenTool,
  ServerCog,
  ShieldCheck,
  Sparkles,
  X,
} from "lucide-react";
import type { LucideIcon } from "lucide-react";

import { Navbar } from "@/components/navbar";
import { ParticlesBackground } from "@/components/particles-background";
import SplashCursor from "@/components/SplashCursor";
import { ToolCard } from "@/components/tool-card";
import { Button } from "@/components/ui/button";
import { categories } from "@/lib/aigc-data";
import { cn } from "@/lib/utils";

const categoryIcons: Record<string, LucideIcon> = {
  Sparkles,
  PenLine,
  Palette,
  Clapperboard,
  Briefcase,
  MessagesSquare,
  PenTool,
  Music,
  ShieldCheck,
  GraduationCap,
  Bot,
  Layers,
  Braces,
  ServerCog,
  Dna,
  Building2,
  Factory,
};

const allSubcategories = categories.flatMap((category) => category.subcategories);
const allTools = allSubcategories.flatMap((subcategory) => subcategory.tools);
const totalTools = allTools.length;
const freeToolShowcase = allTools
  .filter((tool) => tool.tags?.some((tag) => tag.includes("免费")))
  .slice(0, 6);

const flashUpdates = [
  {
    title: "Midjourney v7 正式开放测试",
    time: "15分钟前",
  },
  {
    title: "Suno 发布音乐版权合作计划，支持商用曲库",
    time: "48分钟前",
  },
  {
    title: "通义千问多模态能力升级 Beta 开放",
    time: "2小时前",
  },
];

const sideBusinessIdeas = [
  {
    title: "AI 公众号写作速成营",
    description: "掌握爆款结构 + AIGC 辅助创作，打造矩阵账号。",
  },
  {
    title: "数字人带货直播方案",
    description: "利用 HeyGen 等数字人平台实现 24 小时直播带货。",
  },
  {
    title: "AI 课程知识付费",
    description: "用 AIGC 工具快速搭建知识星球与视频课程。",
  },
];

const industryReports = [
  {
    title: "2024 生成式 AI 产业图谱白皮书",
    provider: "甲子光年",
  },
  {
    title: "全球大模型能力 Benchmark 榜单",
    provider: "斯坦福 HAI",
  },
  {
    title: "中国企业 AIGC 应用落地案例集",
    provider: "德勤咨询",
  },
];

export default function HomePage() {
  const [query, setQuery] = useState("");
  const [isSidebarExpanded, setIsSidebarExpanded] = useState(() => {
    if (typeof window === "undefined") {
      return true;
    }
    return window.matchMedia("(min-width: 1024px)").matches;
  });
  const [isMobileSidebarOpen, setIsMobileSidebarOpen] = useState(false);

  useEffect(() => {
    if (typeof window === "undefined") {
      return;
    }

    const mediaQuery = window.matchMedia("(min-width: 1024px)");
    const handleChange = (event: MediaQueryListEvent) => {
      setIsSidebarExpanded(event.matches);
      if (event.matches) {
        setIsMobileSidebarOpen(false);
      }
    };

    mediaQuery.addEventListener("change", handleChange);

    return () => mediaQuery.removeEventListener("change", handleChange);
  }, []);

  const stats = useMemo(
    () => [
      { label: "主栏目", value: categories.length },
      { label: "子栏目", value: allSubcategories.length },
      { label: "工具库", value: totalTools },
    ],
    []
  );

  const latestTools = useMemo(() => allTools.slice(0, 6), []);

  const normalizedQuery = query.trim().toLowerCase();
  const searchResults = normalizedQuery
    ? categories.flatMap((category) =>
        category.subcategories.flatMap((subcategory) =>
          subcategory.tools
            .filter((tool) => {
              const needle = normalizedQuery;
              return (
                tool.name.toLowerCase().includes(needle) ||
                tool.description.toLowerCase().includes(needle) ||
                tool.tags?.some((tag) => tag.toLowerCase().includes(needle))
              );
            })
            .map((tool) => ({
              categoryId: category.id,
              categoryTitle: category.title,
              subcategoryId: subcategory.id,
              subcategoryTitle: subcategory.title,
              tool,
            })),
        ),
      )
    : [];

  const closeMobileSidebar = () => setIsMobileSidebarOpen(false);
  const toggleMobileSidebar = () => setIsMobileSidebarOpen((open) => !open);
  const toggleSidebarWidth = () => setIsSidebarExpanded((expanded) => !expanded);

  return (
    <main className="min-h-screen bg-muted/20 text-foreground">
      <SplashCursor />
      <Navbar
        onToggleMobileSidebar={toggleMobileSidebar}
        isMobileSidebarOpen={isMobileSidebarOpen}
        onToggleCollapse={toggleSidebarWidth}
        isSidebarExpanded={isSidebarExpanded}
      />

      {isMobileSidebarOpen ? (
        <div
          className="fixed inset-0 z-30 bg-black/40 backdrop-blur-sm lg:hidden"
          onClick={closeMobileSidebar}
          aria-hidden="true"
        />
      ) : null}

      

      <section className="relative mx-auto flex w-full max-w-[1920px] flex-col gap-4 px-4 py-12 sm:px-6 lg:flex-row lg:px-16">
        <aside
          className={cn(
            "fixed inset-y-0 left-0 z-40 flex h-full w-72 flex-col border-r border-border/60 bg-card/95 p-6 shadow-xl transition-transform duration-200 overflow-hidden",
            "lg:fixed lg:inset-y-0 lg:h-screen lg:overflow-y-auto lg:translate-x-0",
            isMobileSidebarOpen ? "translate-x-0" : "-translate-x-full",
            isSidebarExpanded 
              ? "lg:left-4 lg:w-64" 
              : "lg:left-4 lg:w-20 lg:px-4",
          )}
        >
          <ParticlesBackground className="absolute inset-0 pointer-events-none" />
          <div className={cn("mb-6 flex items-center relative z-10", isSidebarExpanded ? "justify-end" : "justify-center")}>
            <Button
              variant="ghost"
              size="icon"
              className="text-muted-foreground hover:text-primary lg:hidden"
              onClick={closeMobileSidebar}
              aria-label="关闭分类导航"
              type="button"
            >
              <X className="size-4" />
            </Button>
            <Button
              variant="ghost"
              size="icon"
              className="hidden text-muted-foreground hover:text-primary lg:flex"
              onClick={toggleSidebarWidth}
              aria-label={isSidebarExpanded ? "收起分类导航" : "展开分类导航"}
              type="button"
            >
              {isSidebarExpanded ? <PanelLeftClose className="size-4" /> : <PanelLeftOpen className="size-4" />}
            </Button>
          </div>

          <nav className="space-y-1 relative z-10">
            {categories.map((category) => {
              const Icon = categoryIcons[category.icon] ?? Sparkles;

              return (
                <a
                  key={category.id}
                  href={`#${category.id}`}
                  className={cn(
                    "group flex items-center rounded-xl px-3 py-2 text-sm font-medium text-foreground/80 transition-all hover:bg-primary/10 hover:text-primary",
                    isSidebarExpanded ? "gap-3 justify-start" : "gap-0 justify-center",
                  )}
                  onClick={(e) => {
                    closeMobileSidebar();
                    e.preventDefault();
                    const element = document.getElementById(category.id);
                    if (element) {
                      const navHeight = 64; // Navbar 高度
                      const offset = 20; // 额外偏移量
                      const yOffset = navHeight + offset;
                      const y = element.getBoundingClientRect().top + window.pageYOffset - yOffset;
                      window.scrollTo({ top: y, behavior: "smooth" });
                    }
                  }}
                >
                  <Icon className="size-5" />
                  {isSidebarExpanded ? <span className="truncate">{category.title}</span> : null}
                </a>
              );
            })}
          </nav>
        </aside>

        <div 
          className={cn(
            "flex-1 min-w-0 space-y-12",
            isSidebarExpanded ? "lg:ml-[calc(1rem+16rem+15px)]" : "lg:ml-[calc(1rem+5rem+15px)]"
          )}
        >
          <section id="overview" className="rounded-3xl border border-border/60 bg-background/95 p-6 sm:p-8 shadow-sm">
             

            <div className="mt-10 space-y-4">
              <div className="flex items-center justify-between">
                <h2 className="text-lg font-semibold text-foreground">最新收录</h2>
                <span className="text-xs font-medium text-muted-foreground/80">持续扩充 · 优先展示近期入库工具</span>
              </div>
              <div className="grid gap-3 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5 xl:grid-cols-6">
                {latestTools.map((tool) => (
                  <ToolCard key={`latest-${tool.name}`} tool={tool} />
                ))}
              </div>
            </div>
          </section>

          <section id="free" className="rounded-3xl border border-primary/30 bg-primary/5 p-6 sm:p-8 shadow-lg shadow-primary/10">
            <div className="flex flex-col gap-3 sm:flex-row sm:items-end sm:justify-between">
              <div>
                <span className="text-xs font-semibold uppercase tracking-[0.3em] text-primary">免费 AI</span>
                <h2 className="mt-1 text-2xl font-semibold">精选免费 AIGC 工具合集</h2>
                <p className="mt-2 text-sm text-primary/80">
                  覆盖写作、绘画、视频、办公等场景，零成本体验最新 AI 助手。
                </p>
              </div>
              <Link href="#recommendations" className="text-sm font-semibold text-primary hover:underline">
                查看全部分类 ↗
              </Link>
            </div>
            <div className="mt-6 grid gap-3 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5 xl:grid-cols-6">
              {freeToolShowcase.map((tool) => (
                <ToolCard key={`free-${tool.name}`} tool={tool} />
              ))}
            </div>
          </section>

          {normalizedQuery ? (
            <section className="space-y-6 rounded-3xl border border-border/60 bg-background/90 p-6 sm:p-8 shadow-sm">
              <div className="flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between">
                <div>
                  <span className="text-xs font-semibold uppercase tracking-[0.3em] text-muted-foreground">搜索结果</span>
                  <h2 className="text-2xl font-semibold">
                    找到 {searchResults.length} 个与 “{query}” 相关的工具
                  </h2>
                </div>
                <button
                  type="button"
                  onClick={() => setQuery("")}
                  className="text-sm font-medium text-primary hover:underline"
                >
                  清空筛选
                </button>
              </div>
              {searchResults.length > 0 ? (
                <div className="grid gap-3 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5 xl:grid-cols-6">
                  {searchResults.map((result) => (
                    <div
                      key={`${result.categoryId}-${result.subcategoryId}-${result.tool.name}`}
                      className="space-y-2"
                    >
                      <span className="text-[11px] font-semibold uppercase tracking-widest text-muted-foreground/70">
                        {result.categoryTitle} · {result.subcategoryTitle}
                      </span>
                      <ToolCard tool={result.tool} />
                    </div>
                  ))}
                </div>
              ) : (
                <div className="rounded-2xl border border-dashed border-border/80 bg-muted/40 p-10 text-center">
                  <h3 className="text-lg font-semibold text-foreground/80">暂未找到匹配的工具</h3>
                  <p className="mt-2 text-sm text-muted-foreground/80">
                    尝试更换关键词，或提交你想要收录的新工具。
                  </p>
                  <Link
                    href="#submit-tool"
                    className="mt-6 inline-flex items-center justify-center rounded-full border border-primary/40 bg-primary/10 px-4 py-2 text-sm font-semibold text-primary transition-colors hover:bg-primary/20"
                  >
                    提交工具
                  </Link>
                </div>
              )}
            </section>
          ) : (
            categories.map((category) => (
              <div key={category.id} className="space-y-4 scroll-mt-6">
                <div id={category.id} className="flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between px-1 scroll-mt-6">
                  <div>
                    <span className="text-xs font-semibold uppercase tracking-[0.3em] text-muted-foreground">
                      {category.title}
                    </span>
                    <h2 className="text-2xl font-semibold text-foreground">{category.description}</h2>
                  </div>
                </div>

                <section className="space-y-8 rounded-3xl border border-border/60 bg-background/90 p-6 sm:p-8 shadow-md shadow-black/5">
                {category.subcategories.map((subcategory) => (
                  <div key={subcategory.id} id={subcategory.id} className="space-y-4">
                    <div className="flex flex-col gap-1 sm:flex-row sm:items-end sm:justify-between">
                      <div>
                        <h3 className="text-lg font-semibold text-foreground">{subcategory.title}</h3>
                        {subcategory.description ? (
                          <p className="text-sm text-muted-foreground/80">{subcategory.description}</p>
                        ) : null}
                      </div>
                      <span className="text-xs font-medium text-muted-foreground/70">
                        共 {subcategory.tools.length} 个工具
                      </span>
                    </div>
                    <div className="grid gap-3 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5 xl:grid-cols-6">
                      {subcategory.tools.map((tool) => (
                        <ToolCard key={`${subcategory.id}-${tool.name}`} tool={tool} />
                      ))}
                    </div>
                  </div>
                ))}
                </section>
              </div>
            ))
          )}

          <section id="flash" className="rounded-3xl border border-border/60 bg-card/80 p-6 sm:p-8 shadow-sm">
            <div className="flex flex-col gap-2 sm:flex-row sm:items-end sm:justify-between">
              <div>
                <span className="text-xs font-semibold uppercase tracking-[0.3em] text-muted-foreground">AI 快讯</span>
                <h2 className="text-2xl font-semibold">实时追踪行业动态</h2>
              </div>
              <Link href="#subscribe" className="text-sm font-medium text-primary hover:underline">
                订阅每日快讯
              </Link>
            </div>
            <div className="mt-6 grid gap-4 md:grid-cols-3">
              {flashUpdates.map((item) => (
                <div key={`flash-${item.title}`} className="rounded-2xl border border-border/60 bg-background/80 px-4 py-5">
                  <p className="text-sm font-medium text-foreground/90">{item.title}</p>
                  <span className="mt-3 inline-flex rounded-full border border-border/60 bg-muted px-3 py-1 text-xs text-muted-foreground/70">
                    {item.time}
                  </span>
                </div>
              ))}
            </div>
          </section>

          <section id="side-business" className="rounded-3xl border border-primary/30 bg-primary/5 p-6 sm:p-8 shadow-lg shadow-primary/10">
            <div className="flex flex-col gap-2 sm:flex-row sm:items-end sm:justify-between">
              <div>
                <span className="text-xs font-semibold uppercase tracking-[0.3em] text-primary">AI 副业</span>
                <h2 className="text-2xl font-semibold text-primary">利用 AIGC 打造你的多元收入</h2>
                <p className="mt-2 text-sm text-primary/80">
                  精选可落地的副业模型，配套工具与操作攻略同步更新。
                </p>
              </div>
              <Link href="https://www.aigc.cn/side-business" className="text-sm font-semibold text-primary hover:underline">
                加入副业社群 →
              </Link>
            </div>
            <div className="mt-6 grid gap-4 md:grid-cols-3">
              {sideBusinessIdeas.map((idea) => (
                <div key={idea.title} className="rounded-2xl border border-primary/40 bg-background/95 p-6 shadow-sm">
                  <h3 className="text-lg font-semibold text-foreground">{idea.title}</h3>
                  <p className="mt-3 text-sm text-muted-foreground/80 leading-relaxed">{idea.description}</p>
                </div>
              ))}
            </div>
          </section>

          <section id="certification" className="rounded-3xl border border-border/60 bg-card/80 p-6 sm:p-8 shadow-sm">
            <div className="flex flex-col gap-2 sm:flex-row sm:items-end sm:justify-between">
              <div>
                <span className="text-xs font-semibold uppercase tracking-[0.3em] text-muted-foreground">AI 证书</span>
                <h2 className="text-2xl font-semibold">官方认证与考试项目</h2>
              </div>
              <Link href="https://www.aigc.cn/certification" className="text-sm font-medium text-primary hover:underline">
                查看报考指南
              </Link>
            </div>
            <div className="mt-6 grid gap-3 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5 xl:grid-cols-6">
              {categories
                .find((category) => category.id === "certification")
                ?.subcategories.flatMap((subcategory) => subcategory.tools)
                .map((tool) => (
                  <ToolCard key={`cert-${tool.name}`} tool={tool} />
                ))}
            </div>
          </section>

          <section id="reports" className="rounded-3xl border border-border/60 bg-background/90 p-6 sm:p-8 shadow-sm">
            <div className="flex flex-col gap-2 sm:flex-row sm:items-end sm:justify-between">
              <div>
                <span className="text-xs font-semibold uppercase tracking-[0.3em] text-muted-foreground">报告</span>
                <h2 className="text-2xl font-semibold">深度行业报告速递</h2>
              </div>
              <Link href="https://www.aigc.cn/reports" className="text-sm font-medium text-primary hover:underline">
                下载合集
              </Link>
            </div>
            <div className="mt-6 grid gap-4 md:grid-cols-3">
              {industryReports.map((report) => (
                <div key={report.title} className="rounded-2xl border border-border/50 bg-card/80 p-6 shadow-sm">
                  <h3 className="text-lg font-semibold">{report.title}</h3>
                  <p className="mt-2 text-sm text-muted-foreground/80">出品方：{report.provider}</p>
                  <Link
                    href="https://www.aigc.cn/reports/detail"
                    className="mt-4 inline-flex text-sm font-medium text-primary hover:underline"
                  >
                    阅读报告 →
                  </Link>
                </div>
              ))}
            </div>
          </section>

          <section
            id="submit-tool"
            className="rounded-3xl border border-border/60 bg-gradient-to-br from-primary/10 via-background/95 to-background/90 p-10 shadow-xl shadow-primary/10"
          >
            <div className="text-center">
              <span className="rounded-full border border-primary/40 bg-primary/10 px-4 py-1 text-xs font-semibold uppercase tracking-[0.3em] text-primary">
                工具提交入口
              </span>
              <h2 className="mt-4 text-3xl font-semibold text-foreground">欢迎提交你正在使用的 AIGC 工具</h2>
              <p className="mt-3 text-base text-muted-foreground/80">
                我们将对工具进行评估与分类，帮助更多创作者发现它。提交后 24 小时内邮件回访。
              </p>
            </div>
            <form className="mt-8 grid gap-4 rounded-3xl border border-border/60 bg-background/95 p-8 text-left">
              <div className="grid gap-2">
                <label htmlFor="tool-name" className="text-sm font-semibold text-muted-foreground">
                  工具名称
                </label>
                <input
                  id="tool-name"
                  required
                  placeholder="如 ChatGPT、Midjourney、飞书妙记..."
                  className="rounded-xl border border-border/60 bg-card px-4 py-3 text-sm outline-none transition-colors focus:border-primary"
                />
              </div>
              <div className="grid gap-2">
                <label htmlFor="tool-link" className="text-sm font-semibold text-muted-foreground">
                  官网链接
                </label>
                <input
                  id="tool-link"
                  type="url"
                  required
                  placeholder="https://"
                  className="rounded-xl border border-border/60 bg-card px-4 py-3 text-sm outline-none transition-colors focus:border-primary"
                />
              </div>
              <div className="grid gap-2">
                <label htmlFor="tool-intro" className="text-sm font-semibold text-muted-foreground">
                  功能亮点
                </label>
                <textarea
                  id="tool-intro"
                  rows={4}
                  placeholder="简要介绍工具功能、目标用户、是否免费等信息"
                  className="rounded-xl border border-border/60 bg-card px-4 py-3 text-sm outline-none transition-colors focus:border-primary"
                />
              </div>
              <button
                type="submit"
                className="inline-flex items-center justify-center rounded-full bg-primary px-6 py-3 text-sm font-semibold text-primary-foreground transition-transform hover:-translate-y-0.5 hover:shadow-lg"
              >
                提交审核
              </button>
            </form>
          </section>
        </div>
      </section>

      <footer id="subscribe" className="border-t border-border/60 bg-background/95 py-10">
        <div className="mx-auto flex max-w-7xl flex-col gap-6 px-4 text-sm text-muted-foreground sm:px-6 lg:flex-row lg:items-center lg:justify-between lg:px-16">
          <div>
            <h3 className="text-base font-semibold text-foreground">AIGC 工具导航</h3>
            <p className="mt-1 text-sm text-muted-foreground">
              帮助你在生成式 AI 时代持续保持灵感 · 产品 · 竞争力。
            </p>
          </div>
          <div className="flex flex-col gap-3 sm:flex-row sm:items-center sm:gap-4">
            <label htmlFor="newsletter" className="text-xs font-semibold uppercase tracking-[0.3em] text-muted-foreground">
              订阅快讯
            </label>
            <div className="flex w-full max-w-md items-center gap-2 rounded-full border border-border/60 bg-card px-3 py-2">
              <input
                id="newsletter"
                type="email"
                placeholder="输入你的邮箱，获取每日 AI 精选"
                className="flex-1 bg-transparent text-sm outline-none placeholder:text-muted-foreground/60"
              />
              <button
                type="submit"
                className="rounded-full bg-primary px-4 py-2 text-xs font-semibold uppercase tracking-widest text-primary-foreground"
              >
                订阅
              </button>
            </div>
          </div>
          <p className="text-xs text-muted-foreground/80">
            © {new Date().getFullYear()} AIGC.cn · 数据来源于公开网络 · 保持探索
          </p>
        </div>
      </footer>
    </main>
  );
}
